package cn.zebra.dev.product.module.cart.service.impl;

import cn.zebra.dev.ibatis.plus.service.impl.ServiceImpl;
import cn.zebra.dev.product.module.cart.dao.CartDao;
import cn.zebra.dev.product.module.cart.entity.CartEntity;
import cn.zebra.dev.product.module.cart.service.CartService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * @author runnable@sina.cn
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartDao, CartEntity> implements CartService {
    @Override
    public Collection<CartEntity> list(Long userId) {
        return baseMapper.list(userId);
    }

    @Override
    public CartEntity findByUserIdAndProductIdAndProductSkuId(Long userId, Long productId, Long productSkuId) {
        return selectOne("user_id = {0} AND product_id = {1} AND product_sku_id = {2} AND delete_flag = FALSE AND buy_flag = FALSE");
    }

    @Override
    public Boolean setNum(Long cartId, Long num, Long userId) {
        return baseMapper.setNum(cartId, num, userId) > 0;
    }

    @Override
    public Boolean deleteCart(Long cartId, Long userId) {
        CartEntity entity = new CartEntity();
        entity.setDeleteFlag(true);
        return update(entity, "id = {0} AND user_id = {1} AND delete_flag = FALSE", cartId, userId);
    }

    @Override
    public Boolean deleteCart(Collection<Long> cartIds, Long userId) {
        CartEntity entity = new CartEntity();
        entity.setDeleteFlag(true);
        UpdateWrapper<CartEntity> wrapper = new UpdateWrapper<>();
        wrapper.in("id", cartIds);
        wrapper.apply("user_id = {0} AND delete_flag = FALSE", userId);
        return update(entity, wrapper);
    }

    @Override
    public Collection<CartEntity> findByIds(Collection<Long> cartIds) {
        QueryWrapper<CartEntity> wrapper = new QueryWrapper<>();
        wrapper.in("id", cartIds);
        wrapper.apply("delete_flag = FALSE");
        return list(wrapper);
    }
}
